// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <melon/benchmark.h>
#include <melon/init/init.h>

#include <pollux/functions/macros.h>
#include <pollux/functions/registerer.h>
#include <pollux/functions/lib/benchmarks/FunctionBenchmarkBase.h>
#include <pollux/common/strings/string_impl.h>
#include <pollux/functions/prestosql/registration/registration_functions.h>

// Benchmark a function that concats its string inputs.

namespace kumo::pollux::functions {

template <typename T>
struct StringConcatSimple {
  POLLUX_DEFINE_FUNCTION_TYPES(T);

  MELON_ALWAYS_INLINE bool call(
      out_type<Varchar>& out,
      const arg_type<Varchar>& str1,
      const arg_type<Varchar>& str2,
      const arg_type<Varchar>& str3,
      const arg_type<Varchar>& str4,
      const arg_type<Varchar>& str5) {
    stringImpl::concatStatic(out, str1, str2, str3, str4, str5);

    return true;
  }
};

template <typename T>
struct StringConcatVariadic {
  POLLUX_DEFINE_FUNCTION_TYPES(T);

  MELON_ALWAYS_INLINE bool call(
      out_type<Varchar>& out,
      const arg_type<Variadic<Varchar>>& strings) {
    for (const auto& string : strings) {
      out += string.value();
    }

    return true;
  }
};

void registerVectorFunction() {
  POLLUX_REGISTER_VECTOR_FUNCTION(udf_concat, "concat_vector");
}

void registerSimpleFunctions() {
  register_function<
      StringConcatSimple,
      Varchar,
      Varchar,
      Varchar,
      Varchar,
      Varchar,
      Varchar>({"concat_simple"});

  register_function<StringConcatVariadic, Varchar, Variadic<Varchar>>(
      {"concat_simple_variadic"});
}

namespace {

class VariadicBenchmark : public functions::test::FunctionBenchmarkBase {
 public:
  VariadicBenchmark() : FunctionBenchmarkBase() {
    registerVectorFunction();
    registerSimpleFunctions();
  }

  RowVectorPtr makeData(vector_size_t numArgs) {
    const vector_size_t size = 1'000;

    std::vector<VectorPtr> args;

    for (vector_size_t i = 0; i < numArgs; ++i) {
      args.emplace_back(
          vectorMaker_.flat_vector<StringView>(size, [](vector_size_t row) {
            return StringView::makeInline(fmt::format("{}", row));
          }));
    }

    return vectorMaker_.row_vector(args);
  }

  size_t run(const std::string& functionName, vector_size_t numArgs = 5) {
    melon::BenchmarkSuspender suspender;
    auto row_vector = makeData(numArgs);

    std::string args;
    for (vector_size_t i = 0; i < numArgs; ++i) {
      if (i > 0) {
        args += ", ";
      }

      args += fmt::format("c{}", i);
    }

    auto exprSet = compileExpression(
        fmt::format("{}({})", functionName, args), row_vector->type());
    suspender.dismiss();

    return doRun(exprSet, row_vector);
  }

  size_t doRun(exec::ExprSet& exprSet, const RowVectorPtr& row_vector) {
    int cnt = 0;
    for (auto i = 0; i < 100; i++) {
      cnt += evaluate(exprSet, row_vector)->size();
    }
    return cnt;
  }

  bool hasSameResults(
      exec::ExprSet& expr1,
      exec::ExprSet& expr2,
      const RowVectorPtr& input) {
    auto result1 = evaluate(expr1, input);
    auto result2 = evaluate(expr2, input);
    if (result1->size() != result2->size()) {
      return false;
    }

    for (auto i = 0; i < result1->size(); i++) {
      if (!result1->equal_value_at(result2.get(), i, i)) {
        return false;
      }
    }
    return true;
  }

  void test() {
    auto input = makeData(5);
    auto exprSetRef =
        compileExpression("concat_vector(c0, c1, c2, c3, c4)", input->type());
    std::vector<std::string> functions = {
        "concat_simple",
        "concat_simple_variadic",
    };

    for (const auto& name : functions) {
      auto other = compileExpression(
          fmt::format("{}(c0, c1, c2, c3, c4)", name), input->type());
      if (!hasSameResults(exprSetRef, other, input)) {
        POLLUX_UNREACHABLE(fmt::format("testing failed at function {}", name));
      }
    }
  }
};

BENCHMARK_MULTI(simple) {
  VariadicBenchmark benchmark;
  return benchmark.run("concat_simple");
}

BENCHMARK_MULTI(vectorVariadic) {
  VariadicBenchmark benchmark;
  return benchmark.run("concat_vector");
}

BENCHMARK_MULTI(simpleVariadic) {
  VariadicBenchmark benchmark;
  return benchmark.run("concat_simple_variadic");
}

BENCHMARK_MULTI(vectorVariadicLotsOfArgs) {
  VariadicBenchmark benchmark;
  return benchmark.run("concat_vector", 100);
}

BENCHMARK_MULTI(simpleVariadicLotsOfArgs) {
  VariadicBenchmark benchmark;
  return benchmark.run("concat_simple_variadic", 100);
}
} // namespace
} // namespace kumo::pollux::functions

int main(int argc, char** argv) {
  melon::Init init{&argc, &argv};
  kumo::pollux::functions::VariadicBenchmark benchmark;
  benchmark.test();
  melon::runBenchmarks();
  return 0;
}
